import './index.scss';
import React, { useState, useMemo, useRef, useEffect } from 'react';
import { useRequest } from 'umi';
import {
  Form,
  Input,
  Tooltip,
  Cascader,
  Select,
  Row,
  Col,
  Button,
  AutoComplete,
  TreeSelect,
  Radio,
  InputNumber,
  Tree,
  message,
  Spin,
} from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { listMenu, roleMenuTreeselect } from '../../Menu/service';
import { addRole, updateRole } from '../service';
import { handleTree } from '@/utils';
import ZxModal from '@/components/Modal';

const { Option } = Select;
const { TextArea } = Input;

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 },
  },
};

const MenuTree: React.FC = ({ value = [], onChange }) => {
  const { data: resTreeData, loading: treeLoading } = useRequest(listMenu);
  const treeData = useMemo(() => {
    const tempTreeData = resTreeData
      ? resTreeData.map((m: any) => {
          m.title = m.menuName;
          m.key = `${m.menuId}`;
          return m;
        })
      : [];
    return handleTree(tempTreeData, 'menuId');
  }, [resTreeData]);

  return (
    <Spin spinning={treeLoading}>
      <Tree
        height={300}
        checkable
        treeData={treeData}
        checkedKeys={value}
        checkStrictly={true}
        onCheck={(checkedKeys, { halfCheckedKeys }) => {
          if (onChange) onChange(checkedKeys.checked);
        }}
      />
    </Spin>
  );
};

const RegistrationForm = (props) => {
  const { visible, onClose, onSubmit, values = {}, title } = props;
  const [form] = Form.useForm();

  // 查询角色权限
  const { run: roleMenuRun } = useRequest(() => roleMenuTreeselect(values.roleId), {
    manual: true,
    onSuccess(res) {
      form.setFieldsValue({
        menuIds: res.checkedKeys.map((m) => `${m}`),
      });
    },
    formatResult: (res) => res,
  });
  // 添加角色
  const { loading: addLoading, run } = useRequest(addRole, {
    manual: true,
    onSuccess(res) {
      ref.current.done(false);
      message.success('角色添加成功！');
      onSubmit();
    },
    onError(err) {
      ref.current.done(false);
    },
  });
  // 修改角色
  const { loading: updateLoading, run: updateRun } = useRequest(updateRole, {
    manual: true,
    onSuccess(res) {
      ref.current.done(false);
      message.success('角色修改成功！');
      onSubmit();
    },
    onError(err) {
      ref.current.done(false);
    },
  });

  useEffect(() => {
    if (values.roleId && visible) {
      roleMenuRun();
    } else {
      form.setFieldsValue({
        menuIds: [],
      });
    }

    if (visible && !addLoading && !updateLoading) {
      form.setFieldsValue({
        roleName: values.roleName || '',
        roleKey: values.roleKey || '',
        roleSort: values.roleSort || 0,
        status: values.status || '0',
        remark: values.remark || '',
      });
    }
  }, [visible]);

  const ref = useRef(null);

  return (
    <ZxModal
      ref={ref}
      title={title}
      visible={visible}
      onClose={() => onClose()}
      onSubmit={() => {
        form
          .validateFields()
          .then((res) => form.submit())
          .catch((err) => ref.current.done(false));
      }}
    >
      <Form
        {...formItemLayout}
        form={form}
        name="register"
        onFinish={(formValues) => {
          console.log(formValues);
          if (values.roleId) {
            updateRun({ ...formValues, roleId: values.roleId });
          } else {
            run(formValues);
          }
        }}
        scrollToFirstError
        preserve={false}
      >
        <Form.Item
          name="roleName"
          label="角色名称"
          rules={[
            {
              required: true,
              message: '请填写角色名称',
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          name="roleKey"
          label="权限字符"
          rules={[
            {
              required: true,
              message: '请填写权限字符',
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          name="roleSort"
          label="角色顺序"
          rules={[
            {
              required: true,
              message: '请填写角色顺序',
            },
          ]}
        >
          <InputNumber min={0} />
        </Form.Item>

        <Form.Item
          name="status"
          label="状态"
          rules={[
            {
              required: true,
              message: '请选择状态',
            },
          ]}
        >
          <Radio.Group>
            <Radio value="0">正常</Radio>
            <Radio value="1">停用</Radio>
          </Radio.Group>
        </Form.Item>

        <Form.Item
          name="menuIds"
          label="菜单权限"
          rules={[
            {
              required: true,
              message: '请选择菜单权限',
            },
          ]}
        >
          <MenuTree />
        </Form.Item>

        <Form.Item name="remark" label="备注">
          <TextArea rows={4} />
        </Form.Item>
      </Form>
    </ZxModal>
  );
};

export default (props) => <RegistrationForm {...props} />;
